<template>
  <div class="app-container">

    <el-breadcrumb>
      <el-breadcrumb-item :to="{path:'/index'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <el-form :inline="true" ref="queryForm" :model="query">
      <el-form-item label="姓名" prop="realName">
        <el-input clearable v-model="query.realName" size="small" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="userRoleIds">
        <el-select size="small" filterable clearable
                   v-model="query.userRoleIds"
                   placeholder="用户角色">
          <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">查询</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="margin-bottom:8px">
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain @click="showDialog(undefined)">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" size="small" plain :disabled="selectedIds.length!==1">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" size="small" plain :disabled="!selectedIds.length">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" size="small" plain disabled>导出</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"/>
      <el-table-column label="头像">
        <template #default="scope">
          <el-avatar :src="scope.row.avatar" size="medium" v-if="scope.row.avatar"></el-avatar>
          <el-avatar v-else size="medium">{{ scope.row.realName }}</el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="在线">
        <template #default="scope">
          <span style="color: #67C23A" v-if="scope.row.isOnLine">在线</span>
          <span style="color: #909399" v-else>离线</span>
        </template>
      </el-table-column>
      <el-table-column prop="realName" label="姓名"/>
      <el-table-column prop="cellphone" label="电话"/>
      <el-table-column prop="email" label="邮箱"/>
      <el-table-column prop="enable" label="是否启用">
        <template #default="scope">
          <el-switch v-model="scope.row.enable"
                     :active-value="1"
                     :inactive-value="0"
                     @change="handleEnable(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="角色">
        <template #default="scope">{{ scope.row.userRole.map(e=>e.name).join(", ") }}</template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="300">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="showDialog(scope.row)">修改</el-button>
          <el-popconfirm title="确定重置吗？" @confirm="resetPassword(scope.row)">
            <el-button style="margin-left:8px" slot="reference" size="mini" type="warning">重置密码</el-button>
          </el-popconfirm>
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row)">
            <el-button style="margin:0 8px" slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <el-pagination
        background
        :page-size="query.pageSize"
        :total="total"
        :current-page.sync="query.currentPage"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"/>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" @closed="handleClose" append-to-body>
      <el-form ref="saveOrUpdateForm" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="账号" prop="loginName">
          <el-input v-model="form.loginName" placeholder="输入账号" :readonly="form.id !== undefined"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="输入名字"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="cellphone">
          <el-input v-model="form.cellphone" placeholder="输入手机"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select style="width:100%" clearable multiple v-model="form.userRoleIds" placeholder="选择角色">
            <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import request from "@/http/request";
import qs from "qs";

export default {
  data() {
    return {
      // 查询参数
      query: {
        currentPage: 1,
        pageSize: 5,
        realName: undefined,
        userRoleIds: []
      },
      // 总记录数
      total: 1,
      // 表格数据
      tableData: [],
      // 选择的ids
      selectedIds: [],
      // 对话框标题
      dialogTitle: '',
      // 对话框显示状态
      dialogVisible: false,
      // 表单对象
      form: {
        id: undefined,
        loginName: undefined,
        realName: undefined,
        cellphone: undefined,
        email: undefined,
        enable: undefined,
        userRoleIds: []
      },
      // 验证规则
      rules: {
        loginName: [
          {required: true, message: '账号不能为空', trigger: 'blur'},
          {min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur'}
        ],
        realName: [
          {required: true, message: '姓名不能为空', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        cellphone: [
          {required: true, message: '手机号不能为空', trigger: 'blur'},
          {pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {pattern: /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/, message: '请输入正确的邮箱', trigger: 'blur'}
        ]
      },
      // 角色列表
      roleList: [{"id":1,"name":"管理"},{"id":2,"name":"运营"},{"id":3,"name":"普通"}]
    };
  },
  methods: {
    listData() {
      // TODO 发送异步请求处理 ...
      /*request({
        url: '/api/sys/user/list',
        method: 'get',
        params: this.query
      }).then(res => {
        this.total = res.data.total;
        this.tableData = res.data.list;
      });*/
      // 以下是模拟服务端响应的用户分页对象
      this.total = 22
      this.tableData = [{
        "id": 1,
        "realName": "liangss",
        "loginName": "liangss",
        "avatar": "/images/avatar01.png",
        "cellphone": "15578894732",
        "email": "136270758@qq.com",
        "enable": 1,
        "userRole": [{"id": 1, "name": "管理"}],
        "isOnLine": true
      }, {
        "id": 2,
        "realName": "dandan",
        "loginName": "dandan",
        "avatar": "/images/avatar02.png",
        "cellphone": "12345678901",
        "email": "dandan@qq.com",
        "enable": 1,
        "userRole": [{"id": 2, "name": "运营"}],
        "isOnLine": false
      }, {
        "id": 3,
        "realName": "huahua",
        "loginName": "huahua",
        "avatar": "/images/avatar03.png",
        "cellphone": "12345678902",
        "email": "huahua@qq.com",
        "enable": 0,
        "userRole": [{"id": 3, "name": "普通"}],
        "isOnLine": false
      }]
      window.scrollTo(0, 0)
    },
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
      console.log(this.selectedIds)
    },
    handleQuery() {
      this.query.currentPage = 1
      this.listData()
    },
    resetQuery() {
      this.$refs['queryForm'].resetFields()
      this.handleQuery()
    },
    handleCurrentChange(val) {
      this.query.currentPage = val
      this.listData()
    },
    handleSizeChange(val) {
      this.query.pageSize = val
      this.listData()
    },
    handleDelete(row) {
      request({
        url: `/api/sys/user/${row.id}/delete`,
        method: 'post'
      }).then(res => {
        this.$message.success('删除用户成功')
        this.listData();
      });
    },
    handleEnable(row) {
      if (row.enable === 0) {
        // 启用操作
        request({
          url: `/api/sys/user/${row.id}/enable`,
          method: 'post'
        }).then(res => {
          row.enable = 1;
          this.$message.success('启用成功')
        });
      } else {
        // 禁用操作
        request({
          url: `/api/sys/user/${row.id}/disable`,
          method: 'post'
        }).then(res => {
          row.enable = 0;
          this.$message.success('禁用成功')
        });
      }
    },
    resetPassword(row) {
      // TODO ...
      console.log('开始处理重置密码操作 ...')
    },
    showDialog(row) {
      if (row) {
        this.dialogTitle = '修改用户'
        // TODO 查询要修改的数据回显 ...
        /*request({
          url: `/api/sys/user/${row.id}`,
          method: 'get'
        }).then(res => {
          this.form = res.data;
        });*/
        // 模拟查询服务器响应的数据
        this.form = JSON.parse(JSON.stringify(row))
        this.dialogVisible = true
      } else {
        this.dialogTitle = '新增用户'
        this.dialogVisible = true
      }
    },
    saveOrUpdate() {
      this.$refs['saveOrUpdateForm'].validate(valid => {
        if (!valid) {
          this.$message.error('请正确填写参数')
          return false
        }
        console.log(this.form)
        if (this.form.id) {
          // 修改操作
          request({
            url: '/api/sys/user/update',
            method: 'post',
            data: qs.stringify(this.form)
          }).then(res => {
            this.$message.success('修改成功')
            this.dialogVisible = false
            this.listData()
          })
        } else {
          // 新增操作
          request({
            url: '/api/sys/user/addnew',
            method: 'post',
            data: qs.stringify(this.form)
          }).then(res => {
            this.$message.success('新增成功')
            this.dialogVisible = false
            this.listData()
          });
        }
      });
    },
    handleClose() {
      this.form = {
        id: undefined,
        loginName: undefined,
        realName: undefined,
        cellphone: undefined,
        email: undefined,
        enable: undefined,
        userRoleIds: []
      };
      this.$refs['saveOrUpdateForm'].resetFields()
      this.dialogVisible = false
    }
  },
  mounted() {
    this.listData()
  }
}
</script>